package edu.scau.ojforwarder.util;

import edu.scau.ojforwarder.bean.NowcoderError;
import edu.scau.ojforwarder.bean.NowcoderSubmission;
import edu.scau.ojforwarder.bean.NowcoderStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.LinkedBlockingQueue;

@Component
public class NowcoderSubmitTask extends Thread {

    @Autowired
    public static NowcoderSubmitTask instance;

    @Autowired
    private NowcoderClient nowcoderClient;

    @Autowired
    private NowcoderStatusManager statusManager;

    @Autowired
    private NowcoderStatusTask nowcoderStatusTask;

    private final LinkedBlockingQueue<NowcoderSubmission> submissionQueue = new LinkedBlockingQueue<>();

    private Logger logger = LoggerFactory.getLogger(NowcoderSubmitTask.class);

    public NowcoderSubmitTask() {
        start();
    }

    @Override
    public void run() {
        while (true) {
            try {
                NowcoderSubmission submission = submissionQueue.take(); // 当列表为空时，会阻塞至列表非空
                String submissionId = submission.getSubmissionId();
                try {
                    String runId = nowcoderClient.submit(submission);
                    if (runId == null)
                        statusManager.setError(submissionId, NowcoderError.OTHER_SUBMIT_EROOR);
                    else {
                        statusManager.addAssociation(runId, submissionId);
                        statusManager.updateStatus(submissionId);
                    }
                } catch (Exception e) {
                    if (e instanceof ErrorException)
                        if (((ErrorException) e).getError() == NowcoderError.CONNECTION_ERROR)
                            submissionQueue.put(submission);
                        else
                            statusManager.setError(submissionId, ((ErrorException) e).getError());
                    else {
                        logger.error("牛客网提交失败！", e);
                        statusManager.setError(submissionId, NowcoderError.OTHER_SUBMIT_EROOR);
                    }
                }
                Thread.sleep(10000);    //连续提交10秒限制
            } catch (InterruptedException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    public String addSubmission(NowcoderSubmission submission) {
        String submissionId = Long.toString(System.currentTimeMillis()) + (int)(Math.random() * 1000);
        submission.setSubmissionId(submissionId);
        NowcoderStatus status = new NowcoderStatus();
        status.setStatus(NowcoderStatus.PENDING);
        status.setDesc("等待提交");
        status.setContestId(submission.getContestId());
        status.setProbNum(submission.getProblemNum());
        statusManager.addStatus(submissionId, status);
        try {
            submissionQueue.put(submission);
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
            statusManager.setError(submissionId, NowcoderError.OTHER_SUBMIT_EROOR);
        }
        nowcoderStatusTask.addSubmission(submissionId, submission.getCallback());
        return submissionId;
    }

}
